import { useOrganStore } from "@/stores";
import request from "@/utils/request";

// 数据缓存
let cache = {
  loaded: false,
};

/**
 * 获取部门
 * @param {*} data
 * @returns
 */
export function listDepts(data) {
  return request({
    // url: "/organ/listDepts",
    url: "/api/flow/user/org/query",
    method: "post",
    data,
  });
}

/**
 * 获取角色
 * @param {*} data
 * @returns
 */
export function listRoles(data) {
  return request({
    // url: "/organ/listRoles",
    url: "/api/flow/user/role/query",
    method: "post",
    data,
  });
}

/**
 * 获取职员
 * @param {*} data
 * @returns
 */
export function listUsers(data) {
  return request({
    // url: "/organ/listUsers",
    url: "/api/flow/user/query",
    method: "post",
    data,
  });
}

export function getUserDetail(params) {
  let { userId } = params;
  if (!userId) {
    console.log("userId is null", params);
    return new Promise((resolve, reject) => {
      reject();
    });
  }

  let userDetail = cache[userId];
  if (userDetail) {
    return new Promise((resolve, reject) => {
      resolve({
        code: 0,
        data: userDetail,
      });
    });
  } else {
    return request({
      url: `/api/flow/user/get/${userId}`,
      method: "get",
      params,
    }).then((resp) => {
      let { code, data: detail } = resp;
      if (code == 0 && detail && detail.name) {
        cache[userId] = resp.data;
      }
      return resp;
    });
  }
}

export function getLoginUserDetail(params) {
  return request({
    url: "/api/auth/current",
    method: "get",
    params,
  });
}

export function loginUserOut() {
  return request({
    url: "/api/auth/logout",
    method: "get",
  });
}

export function loadOrgan() {
  if (!cache.loaded) {
    const { setDepts, setRoles, setUsers } = useOrganStore();
    listDepts({}).then((resp) => {
      if (resp.code == 0) setDepts(resp.data?.records || []);
    });
    listRoles({}).then((resp) => {
      if (resp.code == 0) setRoles(resp.data?.records || []);
    });
    listUsers({}).then((resp) => {
      if (resp.code == 0) setUsers(resp.data?.records || []);
    });
    cache.loaded = true;
  }
}

export default {
  loadOrgan,
  listDepts,
  listRoles,
  listUsers,
  getUserDetail,
  getLoginUserDetail,
  loginUserOut,
};
